package net.huashitong.Indicators.app;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.dataBean.IndexDataDTO;
import net.huashitong.Indicators.dataBean.UserDTO;
import net.huashitong.Indicators.entity.LoginLog;
import net.huashitong.Indicators.entity.MenusAuth;
import net.huashitong.Indicators.entity.UserInfo;
import net.huashitong.Indicators.requestModel.IndexRequestModel;
import net.huashitong.Indicators.service.*;
import net.huashitong.until.Until;
import net.huashitong.user.service.UserAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.List;

import static net.huashitong.Indicators.utils.DataTimeUtils.getLastMonth;

@Controller
@RequestMapping("app/index")
public class IndexController extends JsonBaseController {

    Logger log = LoggerFactory.getLogger(IndexController.class);

    @Override
    protected String getView(String s) {
        return null;
    }

    /*   @Autowired
       private OneIndexService oneIndexService;
       @Autowired
       private TwoIndexService twoIndexService;
       @Autowired
       private ThreeIndexService threeIndexService;
       @Autowired
       private AreaCodeService areaCodeService;*/
    @Autowired
    private HotWordsService hotWordsService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private AppApiService appService;

    @Autowired
    private ChildViewService secondService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserAuthService authService;

    @Autowired
    private IndexDataService indexService;

    @Autowired
    private MenusAuthService menusAuthService;

    /**
     * 欢迎页过滤
     */
    @ResponseBody
    @RequestMapping("/userpower")
    public Message getUserPower(@RequestBody UserDTO dto) {

        UserInfo userInfo = null;
        Map<String, Object> map = new HashMap<>();

        if (StringUtils.isNotBlank(dto.getOpenId())) {
            userInfo = userInfoService.getById(dto.getOpenId());
            if (ObjectUtils.isBlank(userInfo)) {
                map.put("userName", "");
                map.put("localToken", "");
                map.put("openId", "");
                map.put("noRead", "");
                return coverMessage("200", "用户不存在", map);
            }

            //记录登录日志
            LoginLog loginLog = new LoginLog();
            loginLog.setTel(userInfo.getTel());
            loginLog.setUserId(userInfo.getUserId());
            loginLog.setUserName(userInfo.getUserName());
            loginLog.setUserSysId(userInfo.getSysId());
            loginLogService.save(loginLog);

            //是否需要手势编码code
            String code = authService.getCodeValid(userInfo, dto.getEquipCode());
            userInfo.setEquipCode(dto.getEquipCode());
            userInfoService.update(userInfo);
            //获取未读消息个数
            int noReadCount = authService.getNoReadMsgCountByUser(dto.getOpenId());
            map.put("userName", userInfo.getUserName());
            map.put("localToken", userInfo.getLocalToken());
            map.put("openId", userInfo.getSysId());
            map.put("noRead", noReadCount);
            return coverMessage(code, "successful", map);
        }
        map.put("userName", "");
        map.put("localToken", "");
        map.put("openId", "");
        map.put("noRead", "");
        return coverMessage("200", "successful", map);
    }

    /**
     * 主目录
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/catalogue")
    public Message getHomeCatalogue(@RequestBody IndexRequestModel dto) {
        List<Map<String, Object>> list = appService.getHomeIndex(dto.getOpenId(), dto.getDateTime());
        return coverMessage("200", "successful", list);
    }


    /**
     * 二级页面（仪表盘）
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/secondlevel")
    public Message getTwoIndexCatalogue(@RequestBody IndexRequestModel filter) {
        if (StringUtils.isBlank(filter.getCodeType())) {
            filter.setCodeType("Y");
        }
        if (StringUtils.isBlank(filter.getAreaType())) {
            filter.setAreaType("E");
        }
        Map<String, Object> map = secondService.secondCatalogue(filter.getCodeId(),
                filter.getDateTime(),
                filter.getCodeType(),
                filter.getOpenId(),
                filter.getAreaType());
        return coverMessage("200", "successful", map);
    }

    /**
     * 三级页面 基础数据
     */

    @ResponseBody
    @RequestMapping("/thridlevel")
    public Message getThreeIndexCatalogue(@RequestBody IndexRequestModel filter) {
        //默认厦门地区
        if (StringUtils.isBlank(filter.getAreaCode())) {
            filter.setAreaCode("GX350200");
        }
        Map<String, Object> resMap = secondService.thirdCatalogue(
                filter.getCodeId(),
                filter.getDateTime(),
                filter.getAreaCode(),
                filter.getCodeType(),
                filter.getOpenId(),
                filter.getAreaType());
        return coverMessage("200", "successful", resMap);
    }

    /**
     * 市级  areaType D
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/cityView")
    public Message getCityCatalogue(@RequestBody IndexRequestModel filter) {
        log.info("--------------------------接口开始： " + Until.getCurrentDateTime() + " areaType: " + filter.getAreaType()
                + " codeType: " + filter.getCodeType() + " areaCode: "+ filter.getAreaCode()+ "-------------------------------");
        // Map<String ,Object> map  = secondService.secondCatalogue(filter.getCodeId(),filter.getDateTime(),filter.getAreaCode(),"Y");

        // List<Map<String,Object>>  listmap = secondService.thirdCatalogue(filter.getCodeId(),filter.getDateTime(),filter.getAreaCode(),"Y");
        if (StringUtils.isBlank(filter.getCodeType())) {
            filter.setCodeType("Y");
        }
        UserInfo userInfo = userInfoService.getById(filter.getOpenId());
        List map = appService.getCityView("1", filter.getCodeType(), filter.getAreaType(), userInfo);
        log.info("--------------------------接口结束： " + Until.getCurrentDateTime() + " areaType: " + filter.getAreaType()
                + " codeType: " + filter.getCodeType() + " areaCode: "+ filter.getAreaCode()+ "-------------------------------");
        return coverMessage("200", "successful", map);
    }

    /**
     * 全国主要经济指标 G
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/countryview", method = RequestMethod.POST)
    public Message countryView(@RequestBody IndexRequestModel filter) {
        if (StringUtils.isBlank(filter.getCodeType())) {
            filter.setCodeType("Y");
        }
        String yearresponse = null;
        String yearcode = null;
        JSONObject obj = null;
        try {
            yearresponse = Until.HttpGET(Until.GET_DATA_TIME + "db=" + Until.YUEDU_QUANGUO, 5000, 5000);
            obj = JSONObject.parseObject(yearresponse);
            if (200 == obj.getIntValue("returncode")) {
                JSONArray array = obj.getJSONArray("returndata");
                if (array.size() > 0) {
                    yearcode = ((JSONObject) array.get(0)).getString("code");
                }
            }
        } catch (IOException e) {
            // e.printStackTrace();
            System.out.println("接口：" + Until.GET_DATA_TIME + "db=" + Until.YUEDU_QUANGUO);
            yearcode = indexService.getNewCurrentDate(filter.getCodeType(), "G");
        } catch (NullPointerException e) {
            yearcode = indexService.getNewCurrentDate(filter.getCodeType(), "G");
        }
        // yearcode = yearcode.substring(0,4);
        if (StringUtils.isBlank(filter.getAreaType())) {
            filter.setAreaType("G");
        }
        if (StringUtils.isBlank(filter.getDateTime())) {
            filter.setDateTime(yearcode);   //设置最新时间
        }
        if (StringUtils.isBlank(filter.getAreaCode())) {
            filter.setAreaCode("GX000000");
        }
        // List<Map<String, Object>> list = secondService.getCountryView(filter);
        UserInfo userInfo = userInfoService.getById(filter.getOpenId());
        List map = appService.getCityView("1", filter.getCodeType(), filter.getAreaType(), userInfo);
        return coverMessage("200", "successful", map);
    }


    /**
     * 区域对比
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fifteencitydata", method = RequestMethod.POST)
    public Message fifteenCityData(@RequestBody IndexRequestModel filter) {

        String yearResponse;
        String yearCode = null;
        JSONObject obj;
        String db = "";
        //全国
        if ("G".equals(filter.getAreaType())) {
            if ("Y".equals(filter.getCodeType())) {
                db = Until.YUEDU_QUANGUO;
            } else if ("J".equals(filter.getCodeType())) {
                db = Until.JIDU_QUANGUO;
            } else if ("N".equals(filter.getCodeType())) {
                db = Until.NIANDU_QUANGUO;
            }
        }
        //九地市
        if ("E".equals(filter.getAreaType())) {
            if ("Y".equals(filter.getCodeType())) {
                db = Until.YUEDU_9DI;
            } else if ("J".equals(filter.getCodeType())) {
                db = Until.JIDU_9DI;
            } else if ("N".equals(filter.getCodeType())) {
                db = Until.NIANDU_9DI;
            }
        }
        //区级
        if ("A".equals(filter.getAreaType())) {
            if ("Y".equals(filter.getCodeType())||"T".equals(filter.getCodeType())) {
                db = Until.YUEDU_QUJI;
            } else if ("J".equals(filter.getCodeType())) {
                db = Until.JIDU_QUJI;
            } else if ("N".equals(filter.getCodeType())) {
                db = Until.NIANDU_QUJI;
            }
        }
        //四个特区
        if ("B".equals(filter.getAreaType())) {
            if ("Y".equals(filter.getCodeType())) {
                db = Until.YUEDU_TEQU4;
            } else if ("J".equals(filter.getCodeType())) {
                db = Until.JIDU_TEQU4;
            } else if ("N".equals(filter.getCodeType())) {
                db = Until.NIANDU_TEQU4;
            }
        }
        //十五个副省级
        if ("C".equals(filter.getAreaType())) {
            if ("Y".equals(filter.getCodeType())) {
                db = Until.YUEDU_FUSHENGJI15;
            } else if ("J".equals(filter.getCodeType())) {
                db = Until.JIDU_FUSHENGJI15;
            } else if ("N".equals(filter.getCodeType())) {
                db = Until.NIANDU_FUSHENGJI15;
            }
        }
        //市级
        if ("D".equals(filter.getAreaType())) {
            if ("Y".equals(filter.getCodeType())) {
                db = Until.YUEDU_SHIJI;
            } else if ("J".equals(filter.getCodeType())) {
                db = Until.JIDU_SHIJI;
            } else if ("N".equals(filter.getCodeType())) {
                db = Until.NIANDU_SHIJI;
            }
        }
        try {
            yearResponse = Until.HttpGET(Until.GET_DATA_TIME + "db=" + db, 5000, 5000);
            obj = JSONObject.parseObject(yearResponse);
            if (200 == obj.getIntValue("returncode")) {
                JSONArray array = obj.getJSONArray("returndata");
                if (array.size() > 0) {
                    yearCode = ((JSONObject) array.get(0)).getString("code");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("接口：" + Until.GET_DATA_TIME + "db=" + db);
            yearCode = indexService.getNewCurrentDate("Y", "C");
        } catch (NullPointerException e) {
            yearCode = indexService.getNewCurrentDate("Y", "C");
        }

        //第一次，设置默认时间
        if (StringUtils.isBlank(filter.getDateTime())) {
            //四个特区，十五个副省级城市默认数据取值要比其他地方晚1个月
            /*if ("Y".equals(filter.getCodeType()) && ("B".equals(filter.getAreaType())*//*||"C".equals(filter.getAreaType())*//*)) {
                String oldTime = yearCode;
                filter.setDateTime(getLastMonth(oldTime));
            }else{
                filter.setDateTime(yearCode);
            }*/
            filter.setDateTime(yearCode);
        }
        Map<String, Object> list = secondService.fifteencitydata(filter.getCodeId(), filter.getCodeType(), filter.getDateTime(), filter.getAreaType(), filter.getAreaCode());
        return coverMessage("200", "successful", list);
    }

    /**
     * 搜索
     *
     * @param filter openId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchIndex", method = RequestMethod.POST)
    public Message searchIndex(@RequestBody IndexRequestModel filter) {

        if (StringUtils.isBlank(filter.getKeyword())) {
            List<Map<String, Object>> resListMap = new ArrayList<>();
            Set<String> resSet = new HashSet<>();

//            //搜索出热词
//            //需要token
//            String sysId = filter.getOpenId();
//            UserInfo userInfo = userInfoService.getById(sysId);
//            String userId = userInfo.getUserId();
//            String token = userInfo.getToken();
//            //如果token不存在，则去调用接口获取新的token
//            JSONArray result = null;
//            if (StringUtils.isNotBlank(token)) {
//                String url = "&token=" + token;
//                String myInfos = Until.HttpGET(Until.HOT_WORDS_URL_NEED_TOKEN + url, 5000, 5000);
//                JSONObject jsonObject = JSONObject.parseObject(myInfos);
//                if ("200".equals(jsonObject.getString("returncode"))) {
//                    result = jsonObject.getJSONArray("returndata");
//                } else {
//                    //获取最新的token并返回结果
//                    result = getHotWordByUser(userInfo);
//                }
//            } else {
//                //获取最新的token并返回结果
//                result = getHotWordByUser(userInfo);
//            }
//            if(result==null){
//                return coverMessage("200", "热词为空", null);
//            }
//            Object[] obArr = result.toArray();
//            for (int i = 0; i < obArr.length; i++) {
//                resSet.add(obArr[i].toString());
//            }
//            List<String> hots = new ArrayList<>();
//            Iterator<String> it = resSet.iterator();
//            while (it.hasNext()) {
//                String str = it.next();
//                hots.add(str);
//            }
//            if (hots.size() < 10) {
//                for (String h : hots) {
//                    Map<String, Object> hMap = new HashMap<>();
//                    hMap.put("hotWord", h);
//                    resListMap.add(hMap);
//                }
//            } else {
//                for (int i = 0; i < 10; i++) {
//                    Map<String, Object> hMap = new HashMap<>();
//                    hMap.put("hotWord", hots.get(i));
//                    resListMap.add(hMap);
//                }
//            }
//            return coverMessage("200", "热词获取成功", resListMap);

            //不需要token
            String hotWords = null;
            try {
                hotWords = Until.HttpGET(Until.HOT_WORDS_URL, 10000, 10000);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("接口：" + Until.HOT_WORDS_URL);
            }
            if (StringUtils.isBlank(hotWords)) {
                return coverMessage("200", "热词为空", null);
            }
            JSONObject jsonObject1 = JSONObject.parseObject(hotWords);
            if ("200".equals(jsonObject1.getString("returncode"))) {
                JSONArray jsonArray = jsonObject1.getJSONArray("returndata");
                if (jsonArray == null) {
                    return coverMessage("200", "热词为空", null);
                }

                Object[] obArr = jsonArray.toArray();
                for (int i = 0; i < obArr.length; i++) {
                    resSet.add(obArr[i].toString());
                }
                List<String> hots = new ArrayList<>();
                Iterator<String> it = resSet.iterator();
                while (it.hasNext()) {
                    String str = it.next();
                    hots.add(str);
                }
                if (hots.size() < 10) {
                    for (String h : hots) {
                        Map<String, Object> hMap = new HashMap<>();
                        hMap.put("hotWord", h);
                        resListMap.add(hMap);
                    }
                } else {
                    for (int i = 0; i < 10; i++) {
                        Map<String, Object> hMap = new HashMap<>();
                        hMap.put("hotWord", hots.get(i));
                        resListMap.add(hMap);
                    }
                }
                return coverMessage("200", "热词获取成功", resListMap);
            } else {
                return coverMessage("200", "热词为空", null);
            }
        }
        List<IndexDataDTO> listdto = appService.getSearcheData(filter.getKeyword());

        return coverMessage("200", "successful", listdto);
    }


    public JSONArray getHotWordByUser(UserInfo userInfo) {
        String pwd = userInfo.getPwd();
        String userId = userInfo.getUserId();
        //调用接口获取新的token
        String newToken = userInfoService.getToken(userId, pwd);
        //更新token
        userInfo.setToken(newToken);
        userInfoService.update(userInfo);

        String newUrl = "&token=" + newToken;
        String hotwords = null;
        try {
            hotwords = Until.HttpGET(Until.HOT_WORDS_URL_NEED_TOKEN + newUrl, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(Until.HOT_WORDS_URL_NEED_TOKEN + newUrl);
        }
        JSONObject newJsonObject = JSONObject.parseObject(hotwords);
        JSONArray result = newJsonObject.getJSONArray("returndata");
        if ("200".equals(newJsonObject.getString("returncode"))) {
            JSONArray returndata = newJsonObject.getJSONArray("returndata");
            return returndata;
        } else {
            return null;
        }
    }

    /**
     * 权限管理
     *
     * @param dto
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/manageauth", method = RequestMethod.POST)
    public Message manageAuth(@RequestBody IndexRequestModel dto) {
        Map<String, Object> resultMap = new HashMap<>();
        if (ObjectUtils.isNotBlank(dto.getOpenId())) {
            String openId = dto.getOpenId();
            UserInfo userInfo = userInfoService.getById(openId);
            if (userInfo == null) {
                return coverMessage("200", "内部参数出错");
            } else {
                String userId = userInfo.getUserId();
                MenusAuth menusAuthOld = menusAuthService.getByUserId(userId);
                String response = null;
                //调用接口查询
                String url = "usercode=" + userId;
                try {
                    response = Until.HttpGET(Until.HAVE_UN_POWER + url, 5000, 5000);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("权限管理/第三方接口错误，获取失败");
                    System.out.println("json数据解析失败");
                }
                if (response == null) {
                    String[] arrEmp = new String[0];
                    resultMap.put("noRightMenus", arrEmp);
                    resultMap.put("noReadCount", "0");
                    return coverMessage("200", "successful", resultMap);
                }
                if (ObjectUtils.isNotBlank(response)) {
                    //保存获取到的数据
                    JSONObject obj = JSONObject.parseObject(response);
                    if (200 == obj.getIntValue("returncode")) {
                        List<String> unPowers = new ArrayList<>();
                        JSONArray array = obj.getJSONArray("returndata");
                        if (array.size() > 0) {
                            for (int i = 0; i < array.size(); i++) {
                                unPowers.add(array.getJSONObject(i).getString("code"));
                            }
                            StringBuffer sb = new StringBuffer();
                            for (String u : unPowers) {
                                sb.append(u + ";");
                            }
                            String[] arr = sb.toString().split(";");
                            resultMap.put("noRightMenus", arr);
//                            menusAuthOld.setNoRightMenus(sb.toString());
//                            //更新
//                            menusAuthService.update(menusAuthOld);
                        } else {
                            String[] arrEmp = new String[0];
                            resultMap.put("noRightMenus", arrEmp);

//                            menusAuthOld.setNoRightMenus("");
//                            //更新
//                            menusAuthService.update(menusAuthOld);
                        }
                    }
                }
//                MenusAuth menusAuth = menusAuthService.getByUserId(userId);
                /*if (menusAuth == null) {
                    MenusAuth auth = new MenusAuth();
                    auth.setUserId(userId);
                    menusAuthService.save(auth);
                    String[] arrEmp = new String[0];
                    resultMap.put("noRightMenus", arrEmp);
                } else {
                    String menus = menusAuth.getNoRightMenus();
                    if (ObjectUtils.isNotBlank(menus)) {
                        String[] arr = menus.split(";");
                        resultMap.put("noRightMenus", arr);
                    } else {
                        String[] arrEmp = new String[0];
                        resultMap.put("noRightMenus", arrEmp);
                    }
                }*/
            }
            //获取未读消息个数
            int noReadCount = authService.getNoReadMsgCountByUser(dto.getOpenId());
            resultMap.put("noReadCount", noReadCount);
            return coverMessage("200", "successful", resultMap);
        } else {
            return coverMessage("200", "内部参数错误");
        }
    }

}
